package yy;

import com.leetcode.play.红包;

import java.lang.reflect.Array;
import java.util.Arrays;

public class ReverseWords {
    public static void main(String[] args) {
        String s = "  hello world  ";
        String result = reverseWords(s);
        System.out.println(result);
    }

    public static String reverseWords(String s) {
        char[] str = new char[s.length()];
        int t;
        int h = 0;
        int k;
        for (int i = s.length() - 1; i >= 0; i--) {
            if ((s.charAt(i)) == ' ') {
                continue;
            }
            t = i;
            while (s.charAt(t) != ' ' && t >= 0) {
                t--;
                if(t==-1){
                    break;
                }
            }
            k = t + 1;
            while (s.charAt(k) != ' ') {
                str[h] = s.charAt(k);
                h++;
                k++;
                if(k==s.length()){
                    break;
                }
            }
            if(h<s.length()){
                str[h] = ' ';
                h++;
            }
            i = t;
        }

        // 处理末尾多余的空格（如果有）
        if (h > 0 && str[h - 1] == ' ') {
            h--;
        }

        // 仅转换有效长度的字符
        return new String(str, 0, h);

    }
}
